package com.yayo.mangement.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.annotation.ResponseJSONP;
import com.yayo.mangement.authentication.context.UserContext;
import com.yayo.mangement.facade.LoginFacade;
import com.yayo.mangement.info.UserInfo;
import com.yayo.mangement.model.SysUser;
import com.yayo.mangement.req.LoginRequest;
import com.yayo.mangement.response.Response;
import com.yayo.mangement.security.utils.JwtUtil;
import com.yayo.mangement.security.utils.SecurityUtil;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

@RestController
@RequestMapping("/api/sys")
public class SysLoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private LoginFacade loginFacade;

    @PostMapping("/login")
    public Response login(@RequestBody LoginRequest loginRequest, HttpServletResponse response){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
        Authentication authenticate = null;
        try{
            authenticate = authenticationManager.authenticate(authenticationToken);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(authenticate == null){
            throw new RuntimeException("登陆失败");
        }
        UserInfo userInfo = SecurityUtil.getUser();
        String jwtToken = JwtUtil.getToken(userInfo.getUserId().toString(), JSON.toJSONString(userInfo));
        response.setHeader("authorization",jwtToken);
        return Response.ok();
    }

    @PostMapping("/logout")
    public Response logout(){
        return Response.ok();
    }

    @GetMapping("/get")
    public void index(ModelMap modelMap){
        modelMap.put("user", UserContext.getUser());
    }

    @GetMapping("/info")
    public Response<UserInfo> info(){
        UserInfo userInfo = SecurityUtil.getUser();
        return  Response.ok(userInfo);
    }

}
